package com.vxdata.utils.modules.utils.case_8x;

import com.alibaba.fastjson2.JSONObject;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;

/**
 * 腾讯云OCR识别：身份证、驾驶证、身份证
 */
@Component
public class IDCardInfoUtils {


//    private static final String FIELD_SECRET_ID = "AKIDiFVVEhtoSqxoOgiTxA78tOdaGfnfGadQ";//填写secretId - 孙鸿运
//    private static final String FIELD_SECRET_KEY = "XnmVxB8oENFqADzUjgMltlMgiUzDAqFM";//填写secretKey - 孙鸿运
//
//    private static final String FIELD_SECRET_ID = "AKIDve8MJzOWP0KNAgwvf8KFtHOEo79uQggP";//填写secretId - 公司
//    private static final String FIELD_SECRET_KEY = "UigOp0vZw2tTmoa7NM4WirkNjoc9QQ9a";//填写secretKey - 公司
//
//    private static final String FIELD_SECRET_ID = "AKIDHMDrGT8wFKBsOeNPxIOI5ey3tVyTbtUq";//填写secretId
//    private static final String FIELD_SECRET_KEY = "IKGzUkldGvPciZBZi3DAsxpSWLsBE3g5";//填写secretKey
//
//    private static final String FIELD_TENCENT_CLOUD_API = "ocr.tencentcloudapi.com";
//    private static final String FIELD_REGION = "ap-shanghai";


    @Value("${tencent.license.field_secret_id}")
    String FIELD_SECRET_ID;
    @Value("${tencent.license.field_secret_key}")
    String FIELD_SECRET_KEY;
    @Value("${tencent.license.field_tencent_cloud_api}")
    String FIELD_TENCENT_CLOUD_API;
    @Value("${tencent.license.field_region}")
    String FIELD_REGION;

    /**
     * 获取OcrClient.
     *
     * @return ocrClient
     */
    private OcrClient getOcrClient() {
        // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
        Credential cred = new Credential(FIELD_SECRET_ID, FIELD_SECRET_KEY);
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        // 指定接入地域域名(默认就近接入
        httpProfile.setEndpoint(FIELD_TENCENT_CLOUD_API);
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        // 自3.1.80版本开始，SDK 支持打印日志。
        clientProfile.setHttpProfile(httpProfile);
        /**
         * 获取OcrClient对象
         * cred : 认证对象 根据secretId 与 secretKey 获取
         * FIELD_REGION : 地域参数，建议您阅读文档了解地域以及计费情况
         * clientProfile : client选项
         */
        OcrClient ocrClient = new OcrClient(cred, FIELD_REGION, clientProfile);
        return ocrClient;
    }


    /**
     * 身份证识别
     * OCR文档: https://cloud.tencent.com/document/product/866/33524
     *
     * @param imageStr
     * @return
     */
    public JSONObject getIDCardOcr(String imageStr) {
        JSONObject jsonObject = new JSONObject();
        //获取OcrClient.
        OcrClient ocrClient = getOcrClient();
        try {
            IDCardOCRRequest req = new IDCardOCRRequest();
            //写入Base64格式图片
            req.setImageBase64(imageStr);

            // 返回警告信息
//            JSONObject config = new JSONObject();
//            // 复印件警告
//            config.put("CopyWarn", true);
//            req.setConfig(config.toString());

            //解析和返回结果
            IDCardOCRResponse resp = ocrClient.IDCardOCR(req);
            jsonObject.put("code", 200);
            jsonObject.put("data", resp);
            return jsonObject;
        } catch (TencentCloudSDKException e) {
            //e.printStackTrace();
            jsonObject.put("code", 500);
            jsonObject.put("data", e.getMessage());
            return jsonObject;
        }
    }


    /**
     * 驾驶证识别
     * ORC文档: https://cloud.tencent.com/document/product/866/36213
     *
     * @param imageStr
     * @return
     */
    public JSONObject getDriverOcr(String imageStr) {
        JSONObject jsonObject = new JSONObject();
        //获取OcrClient.
        OcrClient ocrClient = getOcrClient();
        try {
            DriverLicenseOCRRequest req = new DriverLicenseOCRRequest();
            //写入Base64格式图片
            req.setImageBase64(imageStr);
            //解析和返回结果
            DriverLicenseOCRResponse resp = ocrClient.DriverLicenseOCR(req);
            jsonObject.put("code", 200);
            jsonObject.put("data", resp);
            return jsonObject;
        } catch (TencentCloudSDKException e) {
//            e.printStackTrace();
            jsonObject.put("code", 500);
            jsonObject.put("data", e.getMessage());
            return jsonObject;
        }
    }

    /**
     * 行驶证识别
     * OCR文档: https://cloud.tencent.com/document/product/866/36209
     *
     * @param imageStr
     * @return
     */
    public JSONObject getVehicleOcr(String imageStr) {
        JSONObject jsonObject = new JSONObject();
        //获取OcrClient.
        OcrClient ocrClient = getOcrClient();
        try {
            VehicleLicenseOCRRequest req = new VehicleLicenseOCRRequest();
            //写入Base64格式图片
            req.setImageBase64(imageStr);
            //解析和返回结果
            VehicleLicenseOCRResponse resp = ocrClient.VehicleLicenseOCR(req);
            jsonObject.put("code", 200);
            jsonObject.put("data", resp);
            return jsonObject;
        } catch (TencentCloudSDKException e) {
//            e.printStackTrace();
            jsonObject.put("code", 500);
            jsonObject.put("data", e.getMessage());
            return jsonObject;
        }
    }

    /**
     * 网络图片转Base64
     *
     * @param remark
     * @return
     */
    private String encodeImgageToBase64(String remark) {
        ByteArrayOutputStream outputStream = null;
        try {
            URL url = new URL(remark);
            BufferedImage bufferedImage = ImageIO.read(url);
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", outputStream);
        } catch (IOException e) {
            return remark;
        }
        BASE64Encoder encoder = new BASE64Encoder();
        String s = encoder.encode(outputStream.toByteArray());
        return s;
    }

    /**
     * 主类测试
     *
     * @param args
     */
    public static void main(String[] args) {
        IDCardInfoUtils describeInstances = new IDCardInfoUtils();
        //网路图片转Base64
        String Driver = describeInstances.encodeImgageToBase64("https://ai.bdstatic.com/file/B1934B4FE1BF4BC38F14621E554CFD41");
        JSONObject idcardOcr = describeInstances.getVehicleOcr(Driver);
        System.out.println(idcardOcr);
    }
}
